from flask import current_app, jsonify, g, request
from ihome.utils.response_code import RET

from . import index_blue
from ihome.models import House,HouseImage,Facility,Area,Order

from ihome.utils.commons import login_required
from ihome.utils.image_storage import storage
from ihome import constants
from manage import db
from datetime import datetime
import datetime as date


@index_blue.route('/user/houses')
@login_required
def my_houses():
    """赵云龙"""
    """我的房屋发布列表"""
    user = g.user
    # 获取数据
    if not user:
        return jsonify(errno=RET.LOGINERR,errmsg='用户未登录')
    try:
        my_houses = House.query.filter(House.user_id == user.id).order_by(House.update_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')
    # 查询结果完整性
    # if not my_houses:
    #     return jsonify(errno=RET.DATAERR,errmsg='暂未发布房源')
    # 遍历写入列表
    if my_houses:
        data = []
        for my_house in my_houses:
            data.append(my_house.to_basic_dict())
        # 返回结果
        return jsonify(data=data, errno=RET.OK,errmsg='OK')
    return jsonify(errno=RET.OK,errmsg='也OK')



@index_blue.route('/areas')
def areas():
    """赵云龙"""
    """城区列表"""
    # 查询数据库
    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')
    # 判断数据完整性
    if not areas:
        return jsonify(errno=RET.DATAERR,errmsg='获取数据为空')
    # 创建城区列表
    area_list = []
    # 将城区以字典形式填入列表
    for area in areas:
        area_list.append(area.to_dict())
    # 保存数据
    data = area_list
    # 返回响应
    return jsonify(errno=RET.OK, errmsg='0', data=data)



@index_blue.route('/houses', methods=['POST','GET'])
@login_required
def issue_houses():
    """常沛杨"""

    """房屋数据搜索"""
    if request.method == 'GET':
        # 获取参数
        area_id = request.args.get('aid')
        start_time_str = request.args.get('sd')
        end_time_str = request.args.get('ed')
        sort_key = request.args.get('sk')
        page = request.args.get('p')
        print(start_time_str)
        print(end_time_str)

        if start_time_str:
            start_time = datetime.strptime(start_time_str,'%Y-%m-%d')
        else:
            start_time = datetime.now()

        if end_time_str:
            end_time = datetime.strptime(end_time_str,'%Y-%m-%d')
        else:
            end_time = start_time+date.timedelta(days=1)

        # 处理参数
        # 处理查询参数
        filters = []
        if area_id:
            try:
                area_id = int(area_id)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DATAERR,errmsg='城区类型错误')
            filters.append(House.area_id == area_id)
        # 处理排序参数
        sort_keys = []
        if sort_key:
                if sort_key == 'new':
                    sort_key = House.update_time.desc()
                elif sort_key == 'looking':
                    sort_key = House.order_count.desc()
                elif sort_key == 'price-des':
                    sort_key = House.price.desc()
                elif sort_key == 'price-inc':
                    sort_key = House.price
                sort_keys.append(sort_key)
        # 处理页面参数
        if page:
            try:
                page = int(page)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DATAERR,errmsg='页数类型错误')
        page = page if page else 1
        # 业务处理
        # 查询所有的房源信息
        try:
            house_list = House.query.filter(*filters).order_by(*sort_keys).all()
        except Exception as e:
            return jsonify(errno=RET.DBERR,errmsg='房屋信息查询错误')

        if not house_list:
            return jsonify(errno=RET.NODATA,errmsg='无房源信息')

        # 获取房源信息
        useless=[]
        for house in house_list:
            try:
                order = Order.query.filter(Order.house_id == house.id, Order.end_date>start_time,Order.begin_date<end_time).all()
            except Exception as e:
                return jsonify(errno=RET.DBERR,errmsg='可用房屋信息查询错误')

            if order:
                useless.append(house)

        for item in useless:
            house_list.remove(item)
        # paginate = house_list.paginate(page, constants.HOME_PAGE_MAX_COUNTS,False)
        #
        # page = paginate.page
        # pages = paginate.pages
        # house_list = paginate.items
        houses = []
        for item in house_list:
            houses.append(item.to_basic_dict())

        pages = int(len(houses)/constants.HOME_PAGE_MAX_COUNTS)+1

        if len(houses)<=constants.HOME_PAGE_MAX_COUNTS:
            return_houses = houses[0:len(houses)]
        elif len(houses)>constants.HOME_PAGE_MAX_COUNTS:
            this_page = (page-1)*constants.HOME_PAGE_MAX_COUNTS
            return_houses = houses[this_page:this_page+constants.HOME_PAGE_MAX_COUNTS-1]

        # 返回结果

        data = {
            'houses':return_houses,
            'total_page':pages
        }
        return jsonify(data=data,errno=RET.OK,errmsg='OK')

    """发布房源"""
    user = g.user
    if not user:
        return jsonify(errno=RET.LOGINERR,errmsg='登录后可发布房源')
    # 获取 请求参数
    title = request.json.get('title')
    price = request.json.get('price')
    area_id = request.json.get('area_id')
    address = request.json.get('address')
    room_count = request.json.get('room_count')
    acreage = request.json.get('acreage')
    unit = request.json.get('unit')
    capacity = request.json.get('capacity')
    beds = request.json.get('beds')
    deposit = request.json.get('deposit')
    min_days = request.json.get('min_days')
    max_days = request.json.get('max_days')
    facility = request.json.get('facility')
    # 判断参数完整性
    if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days, facility]):
        print(title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days, facility)
        return jsonify(errno=RET.DATAERR,errmsg='参数不完整')
    # 类型转换
    try:
        price,room_count,acreage,capacity,deposit,min_days,max_days = int(price),int(room_count),int(acreage),int(capacity),int(deposit),int(min_days),int(max_days)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='类型错误')

    # 价格：￥{{(house.price/100.0) 单价为 分
    price = price * 100
    deposit = deposit * 100

    # 创建模型类对象:
    house = House()

    # 确认设施列表数据的正确性
    for fac in facility:
        try:
            one_fac = Facility.query.get(fac)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='设施数据错误')
        house.facilities.append(one_fac)

    house.title = title
    house.price = price
    house.area_id = area_id
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days
    house.user_id = user.id
    # 保存数据
    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='房源数据保存失败')

    data = {
        'house_id' : house.id
    }
    # 返回结果
    return jsonify(errno=RET.OK,errmsg='OK', data=data)


@index_blue.route('/houses/<int:house_id>/images', methods=['POST'])
@login_required
def house_images(house_id):
    """常沛杨"""
    """上传房源图片"""
    # 判断用户登录状态
    user = g.user
    if not user:
        return jsonify(errno=RET.LOGINERR,errmsg='请重新登录')
    # 获取参数
    image_data = request.files.get('house_image')
    image_house_id = house_id
    # 判断参数完整性
    if not all([image_data,image_house_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='图片未上传')
    # 转换图片二进制数据
    try:
        image_name = image_data.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='图片读取失败')
    # 调用第三方接口
    try:
        image_url = storage(image_name)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='图片存储失败')
    # 创建房屋图片对象
    house_image = HouseImage()
    house_image.house_id = image_house_id
    house_image.url = image_url

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库实例房屋错误')

    house.index_image_url = image_url

    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='数据库添加数据失败')

    # 提交数据
    try:
        db.session.add(house_image)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存图片失败')
    # 返回结果
    data = {
        'url': constants.QINIU_DOMIN_PREFIX + house_image.url
    }
    return jsonify(data=data,errno=RET.OK,errmsg='OK')



@index_blue.route('/houses/<int:house_id>')
@login_required
def house_detail(house_id):
    """米治国"""
    """房屋详情页面"""
    user = g.user
    if not house_id:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        house = House.query.filter(House.id==house_id).first()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='获取房屋详情数据失败')

    if not house:
        return jsonify(errno=RET.NODATA,errmsg='无数据')

    data={
        'user_id':user.id if user else -1,
        'house':house.to_full_dict()
    }
    return jsonify(errno=0,errmsg='OK',data=data)



@index_blue.route('/houses/index')
def index():
    """赵云龙"""
    """首页房屋推荐展示"""
    # 获取数据
    try:
        houses = House.query.order_by(House.order_count.desc(), House.update_time.desc()).limit(5)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')
    # 查询数据完整性
    if not houses:
        return jsonify(errno=RET.DATAERR,errmsg='获取推荐数据失败')
    # 创建返回列表
    data = []
    # 循环遍历,获得单个数据的dict形式
    for house in houses:
        data.append(house.to_basic_dict())
    # 返回结果
    return jsonify(data=data, errno=RET.OK, errmsg='OK')